<!-- banner详情 -->
<template>
    <div class="app-container">
        <el-divider>
            <h3>效果</h3>
        </el-divider>
        <div class="showDiv">
            <el-carousel height="230px" style="width:80%" type="card">
                <el-carousel-item v-for="item in banners" :key="item.id">
                    <el-image
                        style="width: 400px; height: 300px"
                        :src="item.imageUrl"
                        fit="contain"
                        :preview-src-list="srcList"
                    ></el-image>
                </el-carousel-item>
            </el-carousel>
        </div>

        <el-divider>
            <h3>排序</h3>
        </el-divider>
        <el-button type="primary" plain @click="openDialog()">新增</el-button>
        <draggable v-model="banners" @end="onEnd" group="banner" animation="1000" @start="onStart">
            <transition-group>
                <div class="showDiv" shadow="hover" v-for="item in banners" :key="item.id">
                    <el-card style="width:60%">
                        <el-collapse>
                            <el-collapse-item :name="item.id">
                                <template slot="title">
                                    <span style="width:100%">
                                        <span style="float:left">{{item.title}}</span>

                                        <span style="float:right">
                                            <el-button
                                                type="primary"
                                                icon="el-icon-edit"
                                                circle
                                                plain
                                                size="small"
                                                @click.stop="openDialog(item.id)"
                                            ></el-button>
                                            <el-button
                                                type="danger"
                                                icon="el-icon-delete"
                                                circle
                                                plain
                                                size="small"
                                                @click.stop="deleteBanner(item.id)"
                                            ></el-button>
                                        </span>
                                    </span>
                                </template>
                                <el-image
                                    style="width: 100%; height: 100%"
                                    :src="item.imageUrl"
                                    fit="contain"
                                    :preview-src-list="srcList"
                                ></el-image>
                            </el-collapse-item>
                        </el-collapse>
                    </el-card>
                </div>
            </transition-group>
        </draggable>

        <el-dialog
            title="banner"
            :visible.sync="dialogFormVisible"
            @close="closeDialog()"
            width="40%"
        >
            <el-form v-model="banner" >
                <el-form-item label="标题">
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <el-input v-model="banner.title" style="width:60%"></el-input>
                </el-form-item>
                <el-form-item label="跳转链接">
                    <el-input v-model="banner.linkUrl" style="width:60%"></el-input>
                </el-form-item>
                <el-form-item label="图片">
                    <el-upload
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                        :action="BASE_API"
                        class="avatar-uploader"
                        :on-progress="fileUploading"
                    >
                        <el-image
                            style="width: 500px; height: 300px"
                            :src="banner.imageUrl"
                            fit="contain"
                            v-if="banner.imageUrl"
                        ></el-image>
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeDialog()">取 消</el-button>
                <el-button type="primary" @click="saveOrUpdateBanner()">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import {
    getBannersByGroupId,
    updateBanners,
    saveBanner,
    getBannerById,
    deleteBannerByIds,
} from "@/api/cms/banner";
import draggable from "vuedraggable";
import { Loading } from "element-ui";
export default {
    //import引入的组件需要注入到对象中才能使用
    components: { draggable },
    props: ["id"],
    data() {
        //这里存放数据
        return {
            banners: [],
            drag: false,
            banner: {},
            dialogFormVisible: false, //控制对话框是否出现
            BASE_API: process.env.BASE_API + "/oss/uploadPhoto",
        };
    },
    //监听属性 类似于data概念
    computed: {
        srcList() {
            return this.banners.map((item) => {
                return item.imageUrl;
            });
        },
    },
    //监控data中的数据变化
    watch: {},
    //方法集合
    methods: {
        getBannersByGroupId() {
            getBannersByGroupId(this.id).then((response) => {
                this.banners = response.data.banners;
            });
        },
        onStart() {
            this.drag = true;
        },
        onEnd() {
            this.drag = false;
            for (let i = 0; i < this.banners.length; i++) {
                this.banners[i].sort = i;
            }
            updateBanners(this.banners).then((response) => {
                this.getBannersByGroupId();
            });
        },
        saveOrUpdateBanner() {
            this.banner.groupId = this.id;
            //修改
            if (this.banner.id) {
                updateBanners([this.banner]).then((response) => {
                    this.getBannersByGroupId();
                    this.closeDialog();
                    this.$message({
                        message: "修改成功",
                        type: "success",
                    });
                });
            }
            //添加
            else {
                this.banner.sort =
                    this.banners.length === 0
                        ? 0
                        : this.banners[this.banners.length - 1].sort + 1;
                saveBanner(this.banner).then((response) => {
                    this.getBannersByGroupId();
                    this.closeDialog();
                    this.$message({
                        message: "添加成功",
                        type: "success",
                    });
                });
            }
        },
        deleteBanner(id) {
            this.$confirm("确定要删除吗？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    deleteBannerByIds([id]).then((response) => {
                        this.getBannersByGroupId();
                        this.$message({
                            type: "success",
                            message: "删除成功!",
                        });
                    });
                })
                .catch(() => {});
        },
        openDialog(id) {
            if (id) {
                getBannerById(id).then((response) => {
                    this.banner = response.data.banner;
                });
            }
            this.dialogFormVisible = true;
        },
        closeDialog() {
            this.banner = {};
            this.dialogFormVisible = false;
        },
        handleAvatarSuccess(res, file) {
            this.$nextTick(() => {
                // 以服务的方式调用的 Loading 需要异步关闭
                this.$forceUpdate();
                this.banner.imageUrl = res.data.url;
                Loading.service().close();
            });
        },

        beforeAvatarUpload(file) {
            const isJPG = file.type === "image/jpeg" || "image/png";
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
                this.$message.error("上传头像图片只能是 JPG或PNG 格式!");
            }
            if (!isLt2M) {
                this.$message.error("上传头像图片大小不能超过 2MB!");
            }
            return isJPG && isLt2M;
        },
        //文件上传是的钩子
        fileUploading(event, file, fileList) {
            Loading.service();
        },
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {},
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {
        this.getBannersByGroupId();
    },
    beforeCreate() {}, //生命周期 - 创建之前
    beforeMount() {}, //生命周期 - 挂载之前
    beforeUpdate() {}, //生命周期 - 更新之前
    updated() {}, //生命周期 - 更新之后
    beforeDestroy() {}, //生命周期 - 销毁之前
    destroyed() {}, //生命周期 - 销毁完成
    activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发，页面一旦激活就会触发
};
</script>
<style scoped>
.showDiv {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
</style>